import { getStoreTemplateAPI } from '@/api/order/lOrder'
import { cloneDeep, isValid } from '@/utils'
// 费用 简称 和 id 的对应关系
let config = {
  basicFee: 0, // 基础费用
  addServiceFee: 1, // 增值服务费
  preferentialFee: 2, // 优惠费
  otherFee: 3, // 其他费用
  extraFee: 4, // 额外费用
  refuseFee: 5, // 退款
  depositFee: 6, // 押金
  returnRefuseFee: 5, // 还车退款
  cancelOrder: -1, // 取消订单
  depositCarRentalFee: 6, // 租车押金
  compensateFee: 17, // 赔款
}
// 费用配置
const feeConfig = {
  basicFee: {
    feeName: '基础费用',
    feeCategory: config['basicFee'],
    readTemplate: false,
    statics: true,
    childrenList: [
      {
        itemName: '月租价（标准）',
        hidden: true,
        unitPrice: true,
        unit: '元/天',
        statics: false,
        costType: 10,
      },
      { itemName: '车辆租金', required: true, costType: 10, statics: true },
      {
        itemName: '手续费（标准）',
        hidden: true,
        unitPrice: true,
        unit: '元/天',
        statics: false,
        costType: 10,
      },
      { itemName: '手续费', costType: 10, statics: true },
      {
        itemName: '基础保险（标准）',
        hidden: true,
        unitPrice: true,
        unit: '元/天',
        statics: false,
        costType: 10,
      },
      { itemName: '基础保险', costType: 10, statics: true },
    ],
  },
  basicStageFee: {
    feeName: '',
    feeCategory: config['basicFee'],
    readTemplate: false,
    statics: true,
    childrenList: [
      { itemName: '车辆租金', required: true, costType: 10, statics: true },
      { itemName: '手续费', costType: 10, statics: true },
      { itemName: '基础保险', costType: 10, statics: true },
    ],
  },
  returnRefuseFee: {
    feeCategory: config['returnRefuseFee'],
    feeName: '退款',
    readTemplate: false,
    statics: true,
    remarkLabel: '还车退款备注',
    childrenList: [{ itemName: '还车退款', statics: true, costType: 20 }],
  },
  returnDepositFee: {
    feeName: '押金退款',
    readTemplate: false,
    statics: false,
    slotName: 'returnDepositFee',
  },
  // 需要读取模板配置 开始
  addServiceFee: {
    feeCategory: config['addServiceFee'],
    readTemplate: true,
    statics: true,
    feeName: '增值服务费',
    childrenList: [],
  },
  preferentialFee: {
    feeCategory: config['preferentialFee'],
    readTemplate: true,
    feeName: '优惠费用',
    statics: true,
    remarkLabel: '优惠备注',
    childrenList: [],
  },
  otherFee: {
    feeCategory: config['otherFee'],
    readTemplate: true,
    feeName: '其他费用',
    statics: true,
    remarkLabel: '其他备注',
    childrenList: [],
  },
  extraFee: {
    feeCategory: config['extraFee'],
    readTemplate: true,
    feeName: '额外费用',
    statics: true,
    remarkLabel: '额外费用备注',
    childrenList: [],
  },
  depositFee: {
    feeCategory: config['depositFee'],
    readTemplate: true,
    feeName: '押金费用',
    statics: false,
    remarkLabel: '押金备注',
    childrenList: [],
  },
  refuseFee: {
    feeCategory: config['refuseFee'],
    readTemplate: true,
    feeName: '退款费用',
    statics: true,
    remarkLabel: '退款备注',
    childrenList: [],
  },
  // 需要读取模板配置 结束
  cancelOrder: {
    feeCategory: config['cancelOrder'],
    feeName: '取消订单',
    statics: true,
    remarkLabel: '取消订单备注',
    childrenList: [
      { itemName: '退款', statics: true, costType: 20 },
      { itemName: '违约金', statics: true, costType: 10 },
    ],
  },
  depositCarRentalFee: {
    feeCategory: config['depositCarRentalFee'],
    feeName: '租车押金',
    readTemplate: true,
    statics: true,
    remarkLabel: '押金备注',
    childrenList: [],
  },
  depositViolationFee: {
    feeName: '违章押金',
    readTemplate: true,
    remarkLabel: '押金备注',
    statics: true,
    childrenList: [{ itemName: '违章押金', required: true, costType: 10, statics: true }],
  },
  returnDepositCarRentalFee: {
    feeName: '退租车押金',
    readTemplate: false,
    statics: true,
    remarkLabel: '退押金备注',
    childrenList: [{ itemName: '退租车押金', disabled: true, costType: 20, statics: true }],
  },
  returnDepositViolationFee: {
    feeName: '退违章押金',
    readTemplate: false,
    statics: true,
    remarkLabel: '退押金备注',
    childrenList: [{ itemName: '退违章押金', disabled: true, costType: 20, statics: true }],
  },
  compensateFee: {
    feeName: '赔款',
    feeCategory: config['compensateFee'],
    readTemplate: false,
    statics: true,
    remarkLabel: '赔款备注',
    compensateReason: 0,
    childrenList: [{ itemName: '赔款', costType: 20, statics: true }],
  },
}
// 组建 costInfoParam
export const buildCostInfoParam = (feeFormValue) => {
  let formOrderFee = feeFormValue.orderFee
  let param = {
    orderFee: [],
  }
  if (formOrderFee.length > 0) {
    formOrderFee.forEach(({ feeType, priceTemplateId, feeNameId, feeDetailList }) => {
      if (feeDetailList.length > 0) {
        feeDetailList = cloneDeep(feeDetailList)
        let computedfeeDetailList = []
        // 将基础费用拆到一级，并删除基础费用 start
        for (let i = 0; i < feeDetailList.length; i++) {
          let feeDetailItem = feeDetailList[i]
          const feeCategory = feeDetailItem.feeCategory
          if (feeCategory == 0 && feeDetailItem.childrenList?.length > 0) {
            // 删除当前项
            feeDetailList.splice(i, 1)
            let childrenList = feeDetailItem.childrenList
            for (let j = childrenList.length - 1; j >= 0; j--) {
              let childrenItem = childrenList[j]
              if (['月租价（标准）', '手续费（标准）', '基础保险（标准）'].includes(childrenItem.itemName)) {
                continue
              }
              let item = {
                ...feeDetailItem,
                ...childrenItem,
                feeCategory: feeCategory,
              }
              delete item.childrenList
              if (childrenItem.itemName == '车辆租金') {
                let rentDailyPrice = childrenList.find((item) => item.itemName == '月租价（标准）')
                if (rentDailyPrice?.amount >= 0) {
                  item.unitPrice = rentDailyPrice.amount
                }
                feeDetailList.splice(i, 0, item)
              } else if (childrenItem.itemName == '手续费') {
                let rentDailyPrice = childrenList.find((item) => item.itemName == '手续费（标准）')
                if (rentDailyPrice?.amount >= 0) {
                  item.unitPrice = rentDailyPrice.amount
                }
                feeDetailList.splice(i, 0, item)
              } else if (childrenItem.itemName == '基础保险') {
                let rentDailyPrice = childrenList.find((item) => item.itemName == '基础保险（标准）')
                if (rentDailyPrice?.amount >= 0) {
                  item.unitPrice = rentDailyPrice.amount
                }
                feeDetailList.splice(i, 0, item)
              } else {
                if (isValid(item.amount)) {
                  feeDetailList.splice(i, 0, item)
                }
              }
            }
            break
          }
        }
        // 将基础费用拆到一级，并删除基础费用 end
        feeDetailList.forEach((feeCategoryItem) => {
          const { type, categoryType, feeCategory, remark, feeNameId, childrenList, id, compensateReason } = feeCategoryItem
          // 处理第三级 childrenList
          if (childrenList) {
            let computedchildrenList = childrenList.map((feeDetailItem) => {
              if (isValid(feeDetailItem.amount) && feeDetailItem.statics) {
                let temp = {
                  itemName: feeDetailItem.itemName,
                  costType: feeDetailItem.costType,
                  amount: feeDetailItem.amount,
                  id: feeDetailItem.id,
                }
                return temp
              } else {
                return undefined
              }
            })
            computedchildrenList = computedchildrenList.filter((item) => item)
            if (computedchildrenList.length > 0 || remark) {
              let option = {
                feeCategory,
                remark,
                feeNameId,
                id,
                compensateReason,
                type: categoryType || 0,
                childrenList: computedchildrenList,
              }
              // 押金（特殊处理），值补充到 param 层上
              if (type == 'depositFee') {
                const { remark, childrenList } = option
                let tempParam = {
                  carDeposit: 0,
                  illegalDeposit: 0,
                  otherDepositList: [],
                  carDepositRemark: remark,
                }
                childrenList.forEach((item) => {
                  const { itemName, amount } = item
                  if (itemName == '租车押金') {
                    tempParam.carDeposit = amount
                  } else if (itemName == '违章押金') {
                    tempParam.illegalDeposit = amount
                  } else {
                    tempParam.otherDepositList.push(item)
                  }
                })
                Object.assign(param, tempParam)
              } else {
                computedfeeDetailList.push(option)
              }
            }
          } else {
            if (isValid(feeCategoryItem.amount) || remark) {
              computedfeeDetailList.push({
                feeCategory,
                remark,
                feeNameId,
                compensateReason,
                itemName: feeCategoryItem.itemName,
                amount: feeCategoryItem.amount,
                unitPrice: feeCategoryItem.unitPrice,
                costType: feeCategoryItem.costType,
                id,
                type: 1,
              })
            }
          }
        })
        param.orderFee.push({
          feeType,
          feeNameId,
          priceTemplateId,
          feeDetailList: computedfeeDetailList,
        })
      } else {
        param.orderFee.push({
          feeType,
          feeNameId,
          priceTemplateId,
          feeDetailList: [],
        })
      }
    })
  }
  return param
}
// 获取门店费用模板
export const getStoreTemplateDetail = (siteId, templateSort, callback) => {
  // 获取门店费用模板 开始
  getStoreTemplateAPI({ siteId, templateSort }).then((res) => {
    const { result } = res
    const feeList = result.tenantPriceFeeList
    const id = result.id
    // 获取门店费用模板 结束
    let template = handleStoreTemplateDetail(feeList)
    template && callback(template, id)
  })
}
// 处理门店费用模板
export const handleStoreTemplateDetail = (feeList) => {
  let temp = {}
  if (feeList) {
    // 处理商户费项
    feeList.forEach((item) => {
      let feeType = item.feeType
      let option = {
        feeType: feeType, // 费用类型
        itemName: item.feeName, // 费用名称
        isSystem: item.isSystem,
        feeAmount: item.feeAmount,
        feeUnit: item.feeUnit, // 0 每次 | 1 每日
      }
      // 处理 payType
      // 0: "收款类型" 1: "付款类型" 2: "收款/付款类型"
      // 此处将 payType 转换成 短租的 10（收款） 和 20（付款）
      let payType = item.payType
      if (payType == 2) {
        // 等于 2 的情况需要用户手动去选收款和付款，默认值设置为收款
        option.costType = 10
        // 显示收付款切换
        option.showCostTypeSwitch = true
      } else {
        option.costType = item.payType == 0 ? 10 : 20
      }
      if (temp[feeType]) {
        temp[feeType].push(option)
      } else {
        temp[feeType] = [option]
      }
    })
  }
  return temp
}
// 对 orderFee 进行数据处理
export const initFeeDetail = async (feeFormVal, storeTemplate) => {
  const orderFee = feeFormVal.orderFee
  orderFee.forEach((feeFormItem) => {
    // 部分费项需要从模板（storeTemplate）中读取费用分类，依据 readTemplate
    compileFeeItemFromTemplate(feeFormItem, storeTemplate)
  })
}
// 自增 key
let randomKey = 0
// 对 feeFormItem > childrenList 费用分类进行补充
export const compileFeeItemFromTemplate = (feeFormItem, storeTemplate) => {
  // 根据 feeFormItem.feeDetailTypeList 转换成 feeFormItem.feeDetailList
  // 业务层配置 feeDetailTypeList（['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee']）
  // 此处读取 feeConfig 配置，转换成 feeDetailList 中的格式
  if (feeFormItem.feeDetailTypeList?.length > 0) {
    feeFormItem.feeDetailList = []
    feeFormItem.feeDetailTypeList.forEach((item) => {
      feeFormItem.feeDetailList.push({
        type: item,
        ...cloneDeep(feeConfig[item]),
        randomKey: randomKey++,
      })
    })
    // feeFormItem.feeDetailTypeList 不再需要，删除冗余数据
    delete feeFormItem.feeDetailTypeList
  }
  // 根据获取到的门店配置（storeTemplate）补充通用费用 feeFormItem.feeDetailTypeList 费用分类
  let feeDetailList = feeFormItem.feeDetailList
  feeDetailList.forEach((feeCategoryItem) => {
    let feeCategory = feeCategoryItem.feeCategory
    // 是否读取模板数据
    let readTemplate = feeCategoryItem.readTemplate
    if (readTemplate) {
      // 根据 feeCategory 获取模板数据
      let storeFeeConfig = storeTemplate[feeCategory]
      if (feeCategoryItem.feeName == '租车押金') {
        // 去掉违章押金
        if (storeFeeConfig?.length > 0) {
          storeFeeConfig = storeFeeConfig.filter((item) => item.itemName != '违章押金')
        }
      }
      if (storeFeeConfig) {
        // 深度克隆
        storeFeeConfig = cloneDeep(storeFeeConfig)
        storeFeeConfig.forEach((item) => {
          // 增值服务费，默认不选中，不统计
          item.statics = feeCategory == 1 ? false : true
          // 押金租金必填
          if (feeCategory == 6) {
            if (item.itemName == '租车押金' || item.itemName == '违章押金') {
              item.required = true
            }
          }
        })
        let currchildrenList = feeCategoryItem.childrenList
        let configDetailList = cloneDeep(storeFeeConfig)
        if (currchildrenList.length > 0) {
          configDetailList.forEach((item) => {
            let findResult = currchildrenList.find((curr) => curr.itemName == item.itemName)
            if (findResult) {
              Object.assign(item, findResult)
            }
          })
        }
        if (feeCategoryItem.disabled) {
          configDetailList = configDetailList.map((item) => {
            return {
              ...item,
              disabled: true,
            }
          })
        }
        feeCategoryItem.childrenList = configDetailList
      }
    }
  })
}

// fee rules
export const getOrderFeeRules = (orderFee) => {
  let _r = {}
  orderFee.forEach((item, index) => {
    let tempFeeDetailList = item.feeDetailList
    tempFeeDetailList.forEach((item2, index2) => {
      let childrenList = item2.childrenList
      if (childrenList?.length > 0) {
        childrenList.forEach((item3, index3) => {
          if (item3.required) {
            let propKey = `orderFee.${index}.feeDetailList.${index2}.childrenList.${index3}.amount`
            _r[propKey] = {
              type: 'number',
              required: true,
              message: '请输入金额',
            }
          }
        })
      }
    })
  })
  return _r
}

// 处理增值服务费默认值
export const handleAddserviceDefaultFee = (feeDetailList, storeTemplate, rate) => {
  feeDetailList.forEach((feeCategory) => {
    const { type, childrenList } = feeCategory
    if (type == 'addServiceFee') {
      let templateAddserviceFee = storeTemplate[1]
      // 日租价 车辆租金 手续费 基础保险
      childrenList.forEach((feeItem) => {
        const { itemName } = feeItem
        let templateItem = templateAddserviceFee.find((item) => item.itemName == itemName)
        // 用户自定义费用
        if (templateItem && !templateItem.isSystem) {
          const { feeUnit, feeAmount } = templateItem
          let amount = undefined
          // 每日
          if (feeUnit == 1) {
            amount = rate * feeAmount
          }
          // 每次
          if (feeUnit == 0) {
            amount = feeAmount
          }
          feeItem.amount = amount
        }
      })
    }
  })
}
